package yesjava.news.web;

import yesjava.news.entity.News;
import yesjava.news.service.NewsService;
import yesjava.news.service.NewsServiceImpl;
import yesjava.news.utils.JSONUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/submit_add.do")
public class SubmitAddNewsServlet extends HttpServlet {
    private NewsService newsService = new NewsServiceImpl();
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        Integer id = Integer.parseInt(request.getParameter("id"));
        String title = request.getParameter("title");
        String content = request.getParameter("content");
        String readCountTxt = request.getParameter("readCount");
        Integer readCount = (readCountTxt==null)?0:(Integer.parseInt(readCountTxt.trim())) ;
        String checkedTxt = request.getParameter("checked");
        Integer checked = (checkedTxt==null)?0:(Integer.parseInt(checkedTxt.trim())) ;

        String showTxt = request.getParameter("show");
        Integer show = (showTxt==null)?0:(Integer.parseInt(showTxt.trim())) ;


        News news = new News().setTitle(title).setContent(content).setReadCount(readCount).setShow(show).setChecked(checked).setCreatorBy(2);
        Integer currentUserId = (Integer) request.getSession().getAttribute("currentUserId");
        if(currentUserId!=null){
            news.setCreatorBy(currentUserId);
        }


//        newsService.updateById(news);

        newsService.saveNews(news);
        Map<String,Object> map  = new HashMap<>();
        map.put("success",true);
        JSONUtil.printJSON(map,response);



    }
}
